package com.promise.jokerdream.database.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.promise.jokerdream.database.entity.UserAccountEntity
import kotlinx.coroutines.flow.Flow

/**
 * 用户账户数据访问对象
 */
@Dao
interface UserAccountDao {
    
    /**
     * 插入或更新用户账户
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(account: UserAccountEntity)
    
    /**
     * 更新用户账户
     */
    @Update
    suspend fun update(account: UserAccountEntity)
    
    /**
     * 根据用户ID获取账户
     */
    @Query("SELECT * FROM user_accounts WHERE userId = :userId LIMIT 1")
    suspend fun getByUserId(userId: String): UserAccountEntity?
    
    /**
     * 根据用户ID获取账户 (Flow)
     */
    @Query("SELECT * FROM user_accounts WHERE userId = :userId LIMIT 1")
    fun getByUserIdFlow(userId: String): Flow<UserAccountEntity?>
    
    /**
     * 获取所有用户账户（先按创建时间升序，次之按账号升序）
     */
    @Query("SELECT * FROM user_accounts ORDER BY createdAt ASC, userId ASC")
    suspend fun getAll(): List<UserAccountEntity>
    
    /**
     * 获取所有用户账户（先按创建时间升序，次之按账号升序）(Flow)
     */
    @Query("SELECT * FROM user_accounts ORDER BY createdAt ASC, userId ASC")
    fun getAllFlow(): Flow<List<UserAccountEntity>>
    
    /**
     * 检查账户是否存在
     */
    @Query("SELECT EXISTS(SELECT 1 FROM user_accounts WHERE userId = :userId)")
    suspend fun exists(userId: String): Boolean
    
    /**
     * 获取账户数量
     */
    @Query("SELECT COUNT(*) FROM user_accounts")
    suspend fun getCount(): Int
    
    /**
     * 删除用户账户
     */
    @Delete
    suspend fun delete(account: UserAccountEntity)
    
    /**
     * 根据用户ID删除账户
     */
    @Query("DELETE FROM user_accounts WHERE userId = :userId")
    suspend fun deleteByUserId(userId: String)
    
    /**
     * 删除所有账户
     */
    @Query("DELETE FROM user_accounts")
    suspend fun deleteAll()
}

